<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>知云——针对编程的个性化学习推荐系统</title>
<%
    pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<base href="${APP_PATH}">
<link rel="shortcut icon" type="image/x-icon" href="${APP_PATH}/static/favicon.ico"/>
<link rel="stylesheet" href="${APP_PATH}/static/css/bootstrap.min.css">
<link rel="stylesheet" href="${APP_PATH}/static/css/toastr.min.css">
<link rel="stylesheet" href="${APP_PATH}/static/css/offcanvas.css">
<link rel="stylesheet" href="${APP_PATH}/static/css/fontawesome.min.css">

<link rel="stylesheet" href="${APP_PATH}/static/css/pell.min.css">
<link rel="stylesheet" href="${APP_PATH}/static/css/input-image-upload.css">

    <style>
        /*限定图片大小样式*/
        div[contenteditable='true'] img {
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>

<body>

<jsp:include page="${APP_PATH}/common/head-question.jsp"/>

<%--提问页面--%>
<div class="mt-2 bg-white rounded p-3 col-sm-12 col-md-12 col-lg-9" style="margin-left: auto;margin-right: auto;">
    <form id="questionForm">
        <%--用户id--%>
        <input type="hidden" name="userid" value="${user.id}"/>
        <%--标题--%>
        <h5 class="border-bottom border-gray pb-2 mb-2">
            <input id="questiontitle" name="questiontitle" type="text" class="col-12 form-control"
                   maxlength="70" placeholder="请输入问题标题，尽量言简意赅">
        </h5>
        <%--内容--%>
        <div id="editor" class="pell"></div>
        <input type="hidden" id="questioncontent" name="questioncontent">
        <div id="html-output" style="display: none"></div>

        <div class="form-inline mt-2">
            <%--领域：获取领域--%>
            <label for="areaid">问题领域:&nbsp;&nbsp;</label>
            <select id="areaid" name="areaid" class="custom-select-sm form-control col-3 col-sm-2">
            </select>

            <a id="btn-submit-question" class="ml-2 btn btn-sm btn-outline-danger">提问</a>

        </div>
    </form>
</div>


<%--图片上传弹出层--%>
<div id="imageUploadDiv"
     class="bg-light rounded border border-danger border-1 shadow-lg p-3"
     style="display: none;z-index: 99;top: 15%;left: 0;right: 0;width: 200px;margin-left:auto;margin-right:auto;position: fixed;">
    <form>
        <div class="form-group">
            <label for="uploaderInput">请选择你要上传的图片:</label>
            <div style="clear: both"></div>
            <div class="input-image-uploader">
                <ul class="input-image-files pl-0" id="uploaderFiles">

                </ul>
                <div class="input-image-box">
                    <input id="uploaderInput" class="input-image" type="file" name="files" accept="image/*">
                </div>
            </div>
            <div style="clear: both"></div>
        </div>
        <div>
            <span id="imgDivInfo">点击图片预览或修改</span>
        </div>
    </form>
    <a id="btn-submit" class="btn btn-sm btn-outline-info disabled">上传</a>
    <a id="btn-cancel" class="btn btn-sm btn-light">取消</a>
</div>

<%--图片预览层--%>
<div class="my-gallery" id="gallery">
    <span class="my-gallery-img" id="galleryImg"></span>
    <div class="my-gallery-option">
        <a href="javascript:void(0);" class="my-gallery-option-icon pt-2 pb-1">
            <i id="icon-delete" class="fa fa-trash-alt fa-2x" style="color: white"></i>
        </a>
    </div>
</div>

<script src="${APP_PATH}/static/js/jquery-3.3.1.min.js"></script>
<script src="${APP_PATH}/static/js/bootstrap.min.js"></script>
<script src="${APP_PATH}/static/js/toastr.min.js"></script>
<script src="${APP_PATH}/static/js/offcanvas.js"></script>
<script src="${APP_PATH}/static/js/pell.min.js"></script>

<script>
    //点击图片上传功能
    function alertImageUploadDiv() {
        $("#imageUploadDiv").show();
    }

    //点击提交按钮
    $("#btn-submit-question").click(function () {
        //校验表单
        var questiontitle = $("#questiontitle").val();
        if (questiontitle.length > 70 || questiontitle.length < 2) {
            toastr.error("请输入字符长度为2-70的标题！");
            return false;
        }
        var areaid = $("#areaid").val();
        if (!areaid) {
            toastr.error("请选择文章领域！");
            return false;
        }
        var $html_out = $("#html-output");
        var questioncontent = $("#questioncontent");
        var content = $html_out.text();
        if (content.length < 10) {
            toastr.error("请输入较为详细的内容");
            return false;
        }
        questioncontent.val(content);
        //开始提交
        $.ajax({
            url: '/postQuestion',
            data: $("#questionForm").serialize(),
            type: 'POST',
            success: function (result) {
                if (result.code === 100) {
                    //跳转到查看问题页面
                    window.location.href = '/question/' + result.extend.questionId;
                    toastr.success("问题发布成功！！");
                } else {
                    toastr.error("问题发布失败！！");
                }
            }
        });
    });

    $(function () {
        //pell容器初始化
        var editor = window.pell.init({
            element: document.getElementById('editor'),
            defaultParagraphSeparator: 'p',
            onChange: function (html) {
                document.getElementById('html-output').textContent = html
            }
        });

        //去掉拼写检查
        $(".pell-content").attr("spellcheck", "false");
        $(".pell-content").addClass("bg-white");

        //获取领域
        $.ajax({
            url: "/allArea",
            method: 'GET',
            success: function (result) {
                if (result.code === 100) {
                    $("#areaid").empty();
                    $("<option disabled selected>请选择:</option>").appendTo($("#areaid"));
                    //插入到select中
                    $.each(result.extend.areas, function (index, item) {
                        var $option = $("<option value='" + item.id + "'>").append(item.areaname);
                        $option.appendTo($("#areaid"));
                    })
                } else {
                    //获取信息失败
                    toastr.error("获取领域失败，请重新登录！！");
                }
            }
        });

        //点击取消按钮
        $("#btn-cancel").click(function () {
            $("#imageUploadDiv").hide();
        });

        //图片上传
        var $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");
        var lil = "";

        //添加图片
        $uploaderInput.on("change", function (e) {
            var src;  //用于图片显示的地址
            var url = window.URL || window.webkitURL || window.mozURL;  //本地地址，用于图片显示的绝对地址
            var files = e.target.files;  //选取的图片文件
            var file = files[0];
            // 过滤掉非图片类型文件
            if (file.type.match('image.*')) {
                if (url) {
                    src = url.createObjectURL(file);
                } else {
                    src = e.target.result;
                }
                var tmpl = '';
                //动态创建li标签，用于显示符合的图片
                tmpl += '<li class="input-image-file"' + 'id="' + file.name + '" style="background-image:url(' + src + ')"></li>';
                $uploaderFiles.append(tmpl);
                ++lil;  //把创建的li标签加1，用于判断图片是否到达规定数目
            }
            if (lil >= 1) {
                //选中1张图片
                $('.input-image-box').css('display', 'none');
                $("#btn-submit").attr("data-flag", "true");
                $("#btn-submit").removeClass("disabled");
            } else {
                $('.input-image-box').css('display', 'block');
            }

        });


        var index;
        var tid;

        /*预览图片*/
        $uploaderFiles.on("click", "li", function () {
            index = $(this).index();
            tid = $(this).attr("id");
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });

        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $("#icon-delete").click(function () {
            $("#uploaderInput").val('');
            //删除该图片的节点
            $uploaderFiles.find("li").eq(index).remove();
            --lil;   //存储li标签的个数减1
            //做判断，如果图片到达9张

            $('.input-image-box').css('display', 'block');
            //修改保存按钮属性
            $("#btn-submit").attr("data-flag", "false");
            $("#btn-submit").addClass("disabled");
        });

        //上传图片
        $("#btn-submit").click(function () {
            //上传图片
            if ($("#btn-submit").attr('data-flag') === "true") {
                //js获取图片对象
                var formFile = new FormData();
                formFile.append("files", document.getElementById("uploaderInput").files[0]);
                $.ajax({
                    url: "/filesUpload",
                    data: formFile,
                    type: "POST",
                    dataType: "json",
                    cache: false,//上传文件无需缓存
                    processData: false,//用于对data参数进行序列化处理 这里必须false
                    contentType: false, //必须
                    success: function (result) {
                        //接收返回的图片路径
                        if (result.code === 100) {
                            //图片上传成功，result.extend.fileList.index0
                            //1.去掉输入框中的文件缓存
                            $("#uploaderInput").val('');
                            //删除该图片的节点
                            $uploaderFiles.find("li").remove();
                            $('.input-image-box').css('display', 'block');
                            //修改按钮属性
                            $("#btn-submit").attr("data-flag", "false");
                            $("#btn-submit").addClass("disabled");
                            //2.将图片插入div中
                            var url = result.extend.fileList.index0;
                            //光标返回到原来编辑的位置
                            $("div[contenteditable='true']").focus();
                            //开始插入图片
                            document.execCommand('InsertImage', false, url);
                            //3.隐藏上传图片框
                            $("#imageUploadDiv").hide();
                            toastr.success("图片上传成功！");
                        } else {
                            toastr.success("图片上传失败，请重试！！！");
                        }
                    }
                })
            } else {
                toastr.error("请先选择图片");
            }
        });
    });
</script>

</body>

</html>
